import { registerCommon } from '@mxpio/common';
import setting from '@/settings/index';
import registerStore from '@/store/index';
import { addBasicRoute, router } from '@/router';
import type { RouteRecordRaw } from 'vue-router';

/**
 * 初始化项目配置项
 * 该方法内会在common实例化前执行
 */
export default async function initApplication() {
  const [{ registerSetting }, { storesInstance }] = await Promise.all([
    import('@mxpio/settings'),
    import('@mxpio/stores'),
  ]);
  // 初始化项目内自定义配置
  registerSetting(setting);
  // 初始化项目内自定义store
  registerStore(storesInstance);
}

export async function initCommon() {
  const [{ defHttp }, { storesInstance }] = await Promise.all([
    // import('@mxpio/router'),
    import('@mxpio/request'),
    import('@mxpio/stores'),
  ]);

  // 为了解耦 `packages/*` 下面各模块与stores、router、request 的依赖关系，不再相互依赖
  // 优先执行桥接模块，保证后续组件初始化正常
  // 初始化桥接模块
  return registerCommon({
    stores: storesInstance,
    router: router,
    defHttp: defHttp,
    env: import.meta.env,
  });
}

/**
 * 初始化项目内私有化配置,例如项目路由等
 * 该方法内会在common实例化后执行，执行需要依赖Commom组件的项目，避免依赖不存在报错
 */
export async function initPackages() {
  // 后续组件待common初始化完成再加载
  const [routerUtils, pages] = await Promise.all([
    import('@mxpio/router-utils'),
    import('@/router/pages'),
  ]);

  const { registerRouter, basicRoutes } = routerUtils;

  // 新增基础路由
  addBasicRoute(basicRoutes as RouteRecordRaw[]);

  // 初始化项目组件地址
  registerRouter({
    pages: pages.default,
  });
}
